package com.demodis.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.demodis.dao.RoleDaoI;
import com.demodis.domain.TblRole;
import com.demodis.util.DBUtil;

public class RoleDaoImpl extends BaseDao implements RoleDaoI {

	@Override
	public List<TblRole> getRoles() {
		String sql = "SELECT * FROM TBL_ROLE;";
		List<TblRole> list = new ArrayList<TblRole>();
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				TblRole role = new TblRole();
				role.setRoleId(rs.getInt("roleId"));
				role.setRoleName(rs.getString("roleName"));
				role.setRoleDes(rs.getString("roleDes"));
				role.setRolePermValue(rs.getInt("rolePermValue"));
				list.add(role);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return list;
	}

	@Override
	public boolean save(TblRole role) {
		String sql = "INSERT INTO TBL_role(ROLENAME, ROLEDES) VALUES(?, ?);";
		conn = DBUtil.getConnection();
		int i = 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, role.getRoleName());
			ps.setString(2, role.getRoleDes());

			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1 ? true : false;
	}

	@Override
	public boolean modify(TblRole role) {
		String sql = "UPDATE TBL_ROLE SET ROLENAME = ?, ROLEDES = ? WHERE ROLEID = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);

			ps.setString(1, role.getRoleName());
			ps.setString(2, role.getRoleDes());
			ps.setInt(3, role.getRoleId());

			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1 ? true : false;
	}

	@Override
	public boolean delete(TblRole role) {
		String sql = "DELETE FROM TBL_ROLE WHERE ROLEID IN(" + role.getIds() + ");";
		int i = 0;
		try {
			conn = DBUtil.getConnection();

			ps = conn.prepareStatement(sql);
			i = ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i > 0 ? true : false;
	}

	@Override
	public boolean distribute(TblRole role) {
		String sql = "UPDATE TBL_USER SET ROLEID = ? WHERE USERID = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);

			ps.setInt(1, role.getRoleId());
			ps.setInt(2, role.getUserId());

			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}

		return i == 1;
	}

}
